﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace Installer.ActiveDirectory
{
    class GroupCheck
    {

        public bool Check_If_Member_Of_AD_Group(string username, string grouptoCheck, string domain)
        {
            System.Diagnostics.Debug.WriteLine("Username: " + username);
            System.Diagnostics.Debug.WriteLine("Group To Check: " + grouptoCheck);
            System.Diagnostics.Debug.WriteLine("Domain: " + domain);
            try
            {

                string EntryString = null;
                EntryString = "LDAP://" + domain;
                DirectoryEntry myDE = default(DirectoryEntry);
                grouptoCheck = grouptoCheck.ToLower();

                myDE = new DirectoryEntry(EntryString);
                DirectorySearcher myDirectorySearcher = new DirectorySearcher(myDE);
                myDirectorySearcher.Filter = "sAMAccountName=" + username;
                myDirectorySearcher.PropertiesToLoad.Add("MemberOf");
                SearchResult myresult = myDirectorySearcher.FindOne();
                int NumberOfGroups = 0;

                NumberOfGroups = myresult.Properties["memberOf"].Count - 1;

                string tempString = null;
                while ((NumberOfGroups >= 0))
                {
                    tempString = myresult.Properties["memberof"][NumberOfGroups].ToString();
                    tempString = tempString.Substring(0, tempString.IndexOf(",", 0));
                    tempString = tempString.Replace("CN=", "");
                    tempString = tempString.ToLower();
                    tempString = tempString.Trim();
                    if ((grouptoCheck == tempString))
                    {
                        return true;

                    }
                    NumberOfGroups = NumberOfGroups - 1;
                }
                return false;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                return false;
            }
        }

    }
}

